import { string } from 'postcss-selector-parser';

export class XReturn {
  private data: object = {
    errcode: 0,
    errmsg: '',
  };

  public setErrCode(errcode: number) {
    this.setData('errcode', errcode);
  }

  public getErrCode(): number {
    return this.getData('errcode');
  }

  public setErrMsg(errmsg: string) {
    this.setData('errmsg', errmsg);
  }

  public getErrMsg(): string {
    return this.getData('errmsg');
  }

  public setData(k: string, v: any) {
    this.data[k] = v;
  }

  public getData(k: string): any {
    return this.data[k];
  }

  public getDataAll(): any {
    return this.data;
  }

  public ok(): boolean {
    return this.getErrCode() === 0;
  }

  public err(): boolean {
    return !this.ok();
  }

  public toString() {
    return JSON.stringify(this.data);
  }
}

function getR(errcode: number, errmsg: string = '') {
  let r = new XReturn();
  r.setErrCode(errcode);
  r.setErrMsg(errmsg);
  return r;
}

export function parse(data: object) {
  if (data instanceof string) {
    data = JSON.parse(data);
  }
  let r = new XReturn();
  for (let key in data) {
    const value = data[key];
    r.setData(key, value);
  }

  return r;
}

export const r = getR(0);
